package com.mmall.common;

import org.codehaus.jackson.annotate.JsonIgnore;
import org.codehaus.jackson.map.annotate.JsonSerialize;

import java.io.Serializable;

/**
 * Created by JINPENG on 2018/10/3.
 */
@JsonSerialize(include =  JsonSerialize.Inclusion.NON_NULL)
//保证序列化jsons,如果是null对象的话，key不会被序列化传到前台
public class ServerResponse<T> implements Serializable{
    private  int stasus;
    private  String msg;
    private  T data;

    private  ServerResponse(int status){
        this.stasus = status;
    }
    private  ServerResponse(int stasus,T data){
            this.stasus = stasus;
            this.data = data;
    }
    private  ServerResponse(int stasus,String msg){
        this.stasus = stasus;
        this.msg = msg;

    }
    private  ServerResponse(int stasus,String msg,T data){
        this.stasus = stasus;
        this.msg = msg;
        this.data = data;
    }

    @JsonIgnore
    //忽略这个方法
    public  boolean isSuccess(){
        return  this.stasus  ==ResponseCode.SUCCESS.getCode();
    }

    public  int getStatus(){
        return  stasus ;
    }

    public T getData(){
        return  data ;
    }

    public  String  getMsg(){
        return  msg ;
    }
//判断是否成功
    public static <T> ServerResponse<T> createBySuccess(){
        return  new ServerResponse<T>(ResponseCode.SUCCESS.getCode());
    }
//只传递msg至前台
    public static <T> ServerResponse<T> createBySuccessMessage(String msg){
        return  new ServerResponse<T>(ResponseCode.SUCCESS.getCode(),msg);
    }
//只传递数据至前台
    public static <T> ServerResponse<T> createBySuccess(T data){
        return  new ServerResponse<T>(ResponseCode.SUCCESS.getCode(),data);
    }
//传递消息及数据至前台
    public static <T> ServerResponse<T> createBySuccess(String msg,T data){
        return  new ServerResponse<T>(ResponseCode.SUCCESS.getCode(),msg,data);
    }
//错误时响应
    public static <T> ServerResponse<T> createByError(){
        return  new ServerResponse<T>(ResponseCode.ERROR.getCode(),ResponseCode.ERROR.getDesc());
    }
//错误时响应的信息
    public static <T> ServerResponse<T> createByErrorMessage(String errorMsg){
        return  new ServerResponse<T>(ResponseCode.ERROR.getCode(),errorMsg);
    }
//错误时响应的状态及信息
    public static <T> ServerResponse<T> createByErrorCodeMessage(int errorCode,String errorMsg){
        return  new ServerResponse<T>(errorCode,errorMsg);
    }
}
